#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
向量库操作主程序
"""

import os
import sys
import logging
from pathlib import Path
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
from fastapi import Request

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn

from vector_system.config.settings import (
    MYSQL_CONFIG, MILVUS_CONFIG, WEB_CONFIG, LOG_CONFIG
)
from vector_system.config.database import create_sqlalchemy_engine
from vector_system.api.routes import api_router

# 创建数据库引擎
engine = create_sqlalchemy_engine()

# 配置日志
logging.basicConfig(
    level=LOG_CONFIG["level"],
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(LOG_CONFIG["file"], encoding='utf-8'),
        logging.StreamHandler(sys.stdout)
    ]
)

logger = logging.getLogger(__name__)

# 创建FastAPI应用
app = FastAPI(
    title="向量库操作系统API",
    description="文件管理、向量库和检索系统，支持多种文件格式的语义检索",
    version="1.0.0"
)

# 挂载静态文件目录
static_dir = os.path.join(project_root, "vector_system", "web", "static")
if os.path.exists(static_dir):
    app.mount("/static", StaticFiles(directory=static_dir), name="static")

# 配置模板
templates_dir = os.path.join(project_root, "vector_system", "web", "templates")
templates = Jinja2Templates(directory=templates_dir) if os.path.exists(templates_dir) else None

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 包含API路由
app.include_router(api_router)

@app.get("/files", response_class=HTMLResponse)
async def files_page(request: Request):
    """文件管理页面"""
    if templates:
        return templates.TemplateResponse("files.html", {"request": request})
    return {"message": "文件管理页面"}

@app.get("/files/{file_id}", response_class=HTMLResponse)
async def file_detail_page(request: Request, file_id: str):
    """文件详情页面"""
    if templates:
        return templates.TemplateResponse("file_detail.html", {"request": request, "file_id": file_id})
    return {"message": f"文件详情页面: {file_id}"}

@app.get("/search", response_class=HTMLResponse)
async def search_page(request: Request):
    """检索页面"""
    if templates:
        return templates.TemplateResponse("search.html", {"request": request})
    return {"message": "内容检索页面"}

@app.get("/stats", response_class=HTMLResponse)
async def stats_page(request: Request):
    """系统统计页面"""
    if templates:
        return templates.TemplateResponse("stats.html", {"request": request})
    return {"message": "系统统计页面"}

@app.on_event("startup")
async def startup_event():
    """应用启动事件"""
    logger.info("启动向量库操作系统...")
    logger.info("正在初始化系统...")
    
    # 初始化数据库表（由file_manager处理）
    logger.info("数据库表由file_manager处理")
    
    # 初始化Milvus集合
    try:
        from vector_system.core.milvus_client import milvus_client
        logger.info("创建Milvus集合...")
        milvus_client.create_collection()
        logger.info("Milvus集合创建完成")
    except Exception as e:
        logger.error(f"创建Milvus集合失败: {e}")
    
    logger.info("系统初始化完成")

@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭事件"""
    logger.info("系统已关闭")
    try:
        if milvus_client.connection:
            milvus_client.close()
    except Exception as e:
        logger.error(f"关闭Milvus连接失败: {e}")

@app.get("/", response_class=HTMLResponse)
async def root(request: Request):
    """根路径 - 返回主页"""
    if templates:
        return templates.TemplateResponse("index.html", {"request": request})
    return {"message": "向量库操作系统已启动"}

@app.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "healthy"}

if __name__ == "__main__":
    logger.info("向量库操作系统启动中...")
    logger.info(f"版本: {app.version}")
    logger.info(f"配置: {WEB_CONFIG}")
    
    uvicorn.run(
        "vector_system.main:app",
        host=WEB_CONFIG["host"],
        port=WEB_CONFIG["port"],
        reload=True
    )